package com.sky.ok.utils;

import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sky
 * @create 2019-05-20 16:59
 **/
@Component
public class CORSFilter extends OncePerRequestFilter {

    /*
     * 在ResponseBodyWrapHandler中已处理跨域问题
     * 但是在shiro验证未通过跳转/unauth时, 因为redirect 重定向会丢失所有请求头，跨域问题重新出现
     * */
    @Override
    protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        httpServletResponse.setHeader("Access-control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");

        System.out.println("IP:"+clientIp(httpServletRequest));

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
      /*  if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            System.out.println("option请求来了");
            }*/
        filterChain.doFilter(servletRequest, servletResponse);

    }

    /**
     * @param request
     * @return
     * @description: 如果通过了多级反向代理的话，
     * X-Forwarded-For的值并不止一个， 而是一串IP值，
     * 究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取 X-Forwarded-For中第一个非unknown的有效IP字符串。
     */
    public static String clientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}